<template>
  <div class="write-article">
    <el-container>
      <el-header>
        <nav-bar></nav-bar>
      </el-header>
      <el-main>
        <div class="editor-container">
          <el-form
            ref="articleFormRef"
            :model="formData"
            :rules="rules"
            label-position="top"
          >
            <el-form-item label="文章标题" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入文章标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="文章标签" prop="tags">
              <el-select
                v-model="formData.tags"
                multiple
                filterable
                placeholder="请选择文章标签"
              >
                <el-option
                  v-for="tag in commonTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>

            <div class="editor-wrapper">
              <div class="editor-header">
                <span class="tab-item" :class="{ active: !isPreview }" @click="isPreview = false">
                  编辑
                </span>
                <span class="tab-item" :class="{ active: isPreview }" @click="isPreview = true">
                  预览
                </span>
              </div>

              <div class="editor-content">
                <template v-if="!isPreview">
                  <el-form-item prop="content">
                    <el-input
                      v-model="formData.content"
                      type="textarea"
                      :rows="20"
                      placeholder="使用 Markdown 格式编写文章内容"
                      resize="none"
                    />
                  </el-form-item>
                </template>
                <template v-else>
                  <div class="preview markdown-body" v-html="renderedContent"></div>
                </template>
              </div>
            </div>

            <div class="form-actions">
              <el-button @click="$router.push('/')">取消</el-button>
              <el-button type="primary" @click="handleSubmit" :loading="submitting">
                发布文章
              </el-button>
            </div>
          </el-form>
        </div>
      </el-main>
      <el-footer>
        <footer-component></footer-component>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'
import hljs from 'highlight.js'
import NavBar from '../components/NavBar.vue'
import FooterComponent from '../components/FooterComponent.vue'

export default {
  name: 'WriteArticle',
  components: {
    NavBar,
    FooterComponent
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const articleFormRef = ref(null)
    const submitting = ref(false)
    const isPreview = ref(false)

    const formData = reactive({
      title: '',
      content: '',
      tags: []
    })

    const commonTags = [
      'Vue.js',
      'React',
      'Node.js',
      'Python',
      'JavaScript',
      '前端开发',
      '后端开发',
      '数据库'
    ]

    const rules = {
      title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' },
        { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
      ],
      tags: [
        { required: true, message: '请选择文章标签', trigger: 'change' }
      ]
    }

    const renderedContent = computed(() => {
      if (!formData.content) return ''

      marked.setOptions({
        highlight: function(code, lang) {
          if (lang && hljs.getLanguage(lang)) {
            return hljs.highlight(code, { language: lang }).value
          }
          return hljs.highlightAuto(code).value
        },
        breaks: true
      })

      return marked(formData.content)
    })

    const handleSubmit = async () => {
      if (!articleFormRef.value) return

      try {
        await articleFormRef.value.validate()
        submitting.value = true

        await store.dispatch('createArticle', {
          title: formData.title,
          content: formData.content,
          tags: formData.tags
        })

        ElMessage.success('文章发布成功')
        router.push('/')
      } catch (error) {
        ElMessage.error(error.message || '发布失败，请重试')
      } finally {
        submitting.value = false
      }
    }

    return {
      articleFormRef,
      formData,
      rules,
      submitting,
      isPreview,
      renderedContent,
      handleSubmit,
      commonTags
    }
  }
}
</script>

<style scoped>
.write-article {
  min-height: 100vh;
}

.el-header {
  padding: 0;
  height: auto;
}

.el-main {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.editor-container {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 20px;
}

.editor-header {
  display: flex;
  border-bottom: 1px solid #dcdfe6;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
}

.tab-item:hover {
  color: #409EFF;
}

.tab-item.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.editor-content {
  min-height: 500px;
}

.preview {
  padding: 20px;
  min-height: 500px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

:deep(.el-textarea__inner) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 14px;
  line-height: 1.6;
}

:deep(.markdown-body) {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif;
}

:deep(.markdown-body pre) {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
}

:deep(.markdown-body code) {
  background-color: rgba(175,184,193,0.2);
  border-radius: 6px;
  padding: 0.2em 0.4em;
  font-size: 85%;
}

:deep(.markdown-body pre code) {
  background-color: transparent;
  padding: 0;
}
</style> 